using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Xml.Linq;

namespace MM.Translator.Model
{
    public class LanguageService
    {
        private static readonly object SyncObject = new object();
        private static LanguageService _languageService = null;

        private IList<LanguageItem> _languageItems = null;

        private LanguageService()
        {
            
        }

        public IList<LanguageItem> GetLanguageItems()
        {
            if (_languageItems == null)
                _languageItems = GetLanguageData();

            return _languageItems;
        }

        public IList<LanguageItem> GetLanguageData()
        {
            var assembly = Assembly.GetExecutingAssembly();

            var resourceStream = Application.GetResourceStream(new Uri(@"/MM.Translator;component/Model/languages.xml", UriKind.RelativeOrAbsolute));
            if (resourceStream == null)
                return null;

            var document = XDocument.Load(resourceStream.Stream);
            var list = document.Element("languages").Elements()
                                                    .Where(e => e.Name == "language")
                                                    .Select(e => new LanguageItem() {Code = e.Attribute("code").Value, Name = e.Attribute("text").Value})
                                                    .ToList();
            return list;
        }

        public static LanguageService Current
        {
            get
            {
                lock (SyncObject)
                {
                    return _languageService ?? (_languageService = new LanguageService());
                }
            }
        }
    }
}